﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using D2DEngine;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using D2DEngine.Scene;
using D2DEngine.Core;
using D2DEngine.Components;
using D2DEngine.Components.AI;
using Microsoft.Xna.Framework.Graphics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using D2DEngine.Util;

namespace AIDev.Components
{
    public enum Direction
    {
        East = 0,
        West = 1,
        North = 2,
        South = 3
    }

    public class EnemyComponent : D2DComponent
    {
        D2DActor actor;
        protected float speed = 1.0f;
        public Direction direction = Direction.East;

        public EnemyComponent()
            : base()
        {
        }

        public EnemyComponent(Direction direction) : 
            base()
        {
            this.direction = direction;
        }

        public EnemyComponent(Direction direction, float speed) :
            base()
        {
            this.direction = direction;
            this.speed = speed;
        }


        public override void OnRegister()
        {
            this.actor = this.owner as D2DActor;

            this.actor.Body.CollisionCategories = Category.Cat2;

            // Give it a push
            this.ApplyInitialImpulse();

            // Cannot colide with another enemy
            this.actor.Body.CollisionCategories = Category.Cat3;
            this.actor.Body.CollidesWith = Category.All & ~Category.Cat3;

            this.actor.Body.BodyType = BodyType.Dynamic;
            this.actor.Body.Restitution = 1.0f;

            base.OnRegister();
        }

        private void ApplyInitialImpulse()
        {
            Vector2 directionVector = Vector2.Zero;
            switch (this.direction)
            {
                case Direction.East:
                    directionVector = new Vector2(1.0f, 0.0f);
                    break;

                case Direction.West:
                    directionVector = new Vector2(-1.0f, 0.0f);
                    break;

                case Direction.South:
                    directionVector = new Vector2(0.0f, 1.0f);
                    break;

                case Direction.North:
                    directionVector = new Vector2(0.0f, -1.0f);
                    break;
            }

            directionVector.Normalize();

            this.actor.Body.ApplyLinearImpulse(directionVector * (this.speed / 10));
        }
    }
}
